package com.auto.survey.activity.monitoring.station

import android.content.Intent
import android.os.Build
import android.text.Spannable
import android.text.SpannableString
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.lifecycle.lifecycleScope
import com.android.identity.util.UUID
import com.auto.survey.R
import com.auto.survey.activity.bluetooth.BluetoolsActivity
import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_PROJET_ID
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MonitorStauts
import com.auto.survey.activity.monitoring.entity.MonitoringObservation
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.entity.MonitoringStation
import com.auto.survey.activity.monitoring.modle.CreateStationViewModle
import com.auto.survey.activity.monitoring.point.CreatePointActivity
import com.auto.survey.base.BaseActivity
import com.auto.survey.base.CustomApplication
import com.auto.survey.geocom.CommandContext
import com.auto.survey.geocom.GeoCom
import com.auto.survey.geocom.GeoComCommon
import com.auto.survey.geocom.GeoComHelper
import com.auto.survey.util.Helper
import com.auto.survey.util.monitoring.entity.CalculationResultWithDetailsTemp
import com.auto.survey.util.monitoring.intersection.RearIntersectionAlgorithm
import com.auto.survey.util.taskqueue.BluetoothTask
import com.auto.survey.util.taskqueue.BluetoothTaskListener
import com.auto.survey.util.taskqueue.BluetoothTaskQueue
import com.auto.survey.util.taskqueue.BluetoothTaskResult
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.dialog.loadingdialog.LoadingDialog
import com.auto.survey.widget.dialog.radiodialog.RadioDialogHelper
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.absoluteValue


class CreateStationActivity : BaseActivity(),OnClickListener{

    companion object {
        val CREATE_STATION_GUESTER_RESULT_OK = 0X5551
        val CREATE_STATION_BASE_POINT_RESULT_OK = 0X5552
        val CREATE_STATION_CHOICKE_POINT_REASULT_OK = 0X5553
        val CREATE_STATION_BASE_POINT = "CREATE_STATION_BASE_POINT"
        val CREATE_STATION_BASE_POINT_TPYE = "CREATE_STATION_BASE_POINT_TPYE"
        val CREATE_STATION_BASE_POINT_LIST = "CREATE_STATION_BASE_POINT_List"
        val CREATE_STATION_CTRL_POINT_LIST = "CREATE_STATION_CTRL_POINT_LIST"

        private val CREATE_STATION_HZ = "horizontalAngle"
        private val CREATE_STATION_VA = "verticalAngle"
        private val CREATE_STATION_SD = "distance"
    }

    private var projectId:Int = -1
    private var objectId:Int = -1
    private lateinit var tvBlueToothState:TextView
    private lateinit var tvMirror:TextView
    private lateinit var tvSelectedMirror:TextView
    private lateinit var tvMeasure:TextView
    private lateinit var edit_cd_name: EditText
    private lateinit var edit_cs_eqhight:EditText
    private lateinit var tv_cs_mirror_c:TextView
    private lateinit var tv_cs_caluation_result: TextView   //计算结果
    private lateinit var tv_cs_caluation_warn: TextView //计算结果警告

    private lateinit var tv_cs_x: TextView  //计算结果测站x坐标
    private lateinit var tv_cs_y: TextView  //计算结果测站y坐标
    private lateinit var tv_cs_z: TextView  //计算结果测站z坐标

    private lateinit var ll_ctrl_point_root:LinearLayout
    private lateinit var ll_obser_point_root:LinearLayout
    private lateinit var ll_cs_caluation_root:LinearLayout

    private var activityLauncher: ActivityResultLauncher<Intent>? = null

    private val database = MonitoringRepository()

    private val bluetoothManager by lazy { BluetoothManagerUtil.getInstance(this) }
    private val geoComHelper: GeoComHelper by lazy { GeoComHelper.getInstance(bluetoothManager) }
    private var isBluetoothConnected = false

    private val viewModel: CreateStationViewModle by viewModels()
    private lateinit var monitorStauts: MonitorStauts
    private var prismType = "-1"    //当前测量的模式
    private var mRadioSelectIndex = -1//棱镜选择的索引
    // 初始化蓝牙任务队列
    private val bluetoothQueue = BluetoothTaskQueue<String>()
    // 单例回调对象
    private var geoComCallback: ((List<GeoCom>, CommandContext) -> Unit)? = null
    private var currentContinuation: CancellableContinuation<BluetoothTaskResult>? = null
    private var isResumed = AtomicBoolean(false) // 使用原子变量确保线程安全

    private var mCtrlPoints = ArrayList<MonitoringPoint>()
    private val mObserPoints = ArrayList<MonitoringPoint>()
    private val mObservations = ArrayList<MonitoringObservation>()
    // 创建并显示加载框
    private var loadingDialog: LoadingDialog?= null

    private var finallCalculationRlt = false    //计算最后结果

    private lateinit var calculationRepository: CalculationResultWithDetailsTemp

    override fun initView() {

        projectId = intent.getIntExtra(KEY_INTENT_PROJET_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("新建测站")

        loadingDialog = LoadingDialog(this)

        tvBlueToothState = findViewById(R.id.tv_bluetooth_state)
        tvMirror = findViewById(R.id.tv_cs_mirror)
        tvMeasure = findViewById(R.id.tv_cs_meausrmodle)
        tv_cs_caluation_result= findViewById(R.id.tv_cs_caluation_result)
        tv_cs_caluation_warn = findViewById(R.id.tv_cs_caluation_warn)
        tv_cs_x = findViewById(R.id.tv_cs_x)
        tv_cs_y = findViewById(R.id.tv_cs_y)
        tv_cs_z = findViewById(R.id.tv_cs_z)
        ll_ctrl_point_root = findViewById(R.id.ll_ctrl_point_root)
        ll_obser_point_root = findViewById(R.id.ll_observ_root)
        ll_cs_caluation_root = findViewById(R.id.ll_cs_caluation_root)
        tvSelectedMirror = findViewById(R.id.tv_cs_docollected_mirror)

        tv_cs_mirror_c = findViewById(R.id.tv_cs_mirror_c)
        edit_cd_name = findViewById(R.id.edit_cs_name)
        edit_cs_eqhight = findViewById<EditText>(R.id.edit_cs_eqhight)


        val view1 = LayoutInflater.from(this@CreateStationActivity).inflate(R.layout.item_create_station_title, ll_ctrl_point_root, false)
        ll_ctrl_point_root.addView(view1)

        val view_obser_title = LayoutInflater.from(this@CreateStationActivity).inflate(R.layout.item_create_station_observ_title, ll_ctrl_point_root, false)
        ll_obser_point_root.addView(view_obser_title)


        tvSelectedMirror.setOnClickListener(this)
        findViewById<ImageView>(R.id.iv_cs_docollected_lightoff).setOnClickListener(this) //关闭激光
        findViewById<ImageView>(R.id.iv_cs_docollected_lighton).setOnClickListener(this) //开启激光
        findViewById<TextView>(R.id.tv_ct_goto_bluetooth).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_goto_gruest_create_station).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_disconnect_bluetooth).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_add_basep).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_choice_basep).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_inseert_basep).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_update_observ_p).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_clear_observ_p).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_caculat_st).setOnClickListener(this)
        findViewById<TextView>(R.id.tv_ct_save_caculat).setOnClickListener(this)

        monitorStauts = MonitorStauts()

        if (bluetoothManager.isBluetoothConnected()) {
            isBluetoothConnected = true
            //1.获取全站仪的型号名称;2、获取偿器的状态;3、获取全站仪角度测量的校正状态;4、获取全站仪当前配置的棱镜类型;
            // 5、获取全站仪的电子测距（EDM）模式; 6、仪器是否整平; 7、获取当前使用的棱镜常数
            geoComHelper.startExecution(listOf( GeoComCommon.CSV_GetInstrumentName, GeoComCommon.TMC_GetInclineSwitch,
                GeoComCommon.TMC_GetAngSwitch, GeoComCommon.BAP_GetPrismType,
                GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetAngle1, GeoComCommon.TMC_GetPrismCorr,
                GeoComCommon.TMC_DoMeasure("3")))
        }


        geoComHelper.onConnectionStateChanged { device, state ->
            if (bluetoothManager.isBluetoothConnected()) {
                CentreToast.instance.show("设备连接成功", true)
                isBluetoothConnected = true

                geoComHelper.startExecution(listOf(GeoComCommon.CSV_GetInstrumentName, GeoComCommon.TMC_GetInclineSwitch,
                    GeoComCommon.TMC_GetAngSwitch, GeoComCommon.BAP_GetPrismType,
                    GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetAngle1, GeoComCommon.TMC_GetPrismCorr,
                    GeoComCommon.TMC_DoMeasure("3")))

            } else {
                isBluetoothConnected = false
            }
        }

        initGeoComCallback()

        // 注册回调（如果尚未注册）
        if (geoComCallback != null && !geoComHelper.isRegisterCallback(geoComCallback!!)) {
            geoComHelper.resultCallback(geoComCallback!!)
        }

        initTaskQueueListener()

        lifecycleScope.launch {

            viewModel.state.observe(this@CreateStationActivity) {
                var strStat = ""
                if (isBluetoothConnected) {
                    strStat = "已连接 "
                } else {
                    strStat = "未连接 "
                }

                strStat = "$strStat#${it.getStauts()}"
                tvBlueToothState.text = strStat
            }

            viewModel.mirrorType.observe(this@CreateStationActivity) {
                //棱镜类型
                Log.i("CreateStationActivity", "viewModel.mirrorType = $it")
                tvMirror.text = "棱镜类型:$it"
            }

            viewModel.measureModle.observe(this@CreateStationActivity) {
                //测量模式
                Log.i("CreateStationActivity", "viewModel.measureModle = $it")
                tvMeasure.text = "测量模式:$it"
            }
        }

        //接收其它页面setResult的返回值， android sdk 更新后 废弃了之前 onActivityForResult
        activityLauncher = registerForActivityResult(StartActivityForResult()) { result: ActivityResult ->
            if (result.resultCode == CREATE_STATION_GUESTER_RESULT_OK) {
                finish()
            }

            if (result.resultCode == CREATE_STATION_BASE_POINT_RESULT_OK) {
                val data = result.data
                if (data != null) {

                    val point = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        data.getParcelableExtra(CREATE_STATION_BASE_POINT, MonitoringPoint::class.java)
                    } else {
                        @Suppress("DEPRECATION")
                        data.getParcelableExtra(CREATE_STATION_BASE_POINT)
                    }

                    if (point != null) {
                        mCtrlPoints.add(point)
                    }
                    updateCtrlPointUI(point)
                }
            }

            if (result.resultCode == CREATE_STATION_CHOICKE_POINT_REASULT_OK) {
                val data = result.data
                if (data != null) {

                    // 兼容新版的 Kotlin 写法
                    val points = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        data.getParcelableArrayListExtra(CREATE_STATION_BASE_POINT_LIST, MonitoringPoint::class.java)
                    } else {
                        @Suppress("DEPRECATION")
                        data.getParcelableArrayListExtra(CREATE_STATION_BASE_POINT_LIST)
                    }
                    Log.i("CreateStationActivity", "points size = ${points?.size}")
                    if (points != null) {
                        mCtrlPoints = points
                    }
                    ll_ctrl_point_root.removeAllViews()
                    val view1 = LayoutInflater.from(this@CreateStationActivity).inflate(R.layout.item_create_station_title, ll_ctrl_point_root, false)
                    ll_ctrl_point_root.addView(view1)

                    //确保mObserPoints是mCtrlPoints的子集
                    mObserPoints.retainAll(mCtrlPoints)

                    points?.forEach {
                        updateCtrlPointUI(it)
                    }

                    updateObserverUI()
                }
            }
        }
    }

    //更新已知控制点UI
    private fun updateCtrlPointUI(point: MonitoringPoint?) {
        val view2 = LayoutInflater.from(this@CreateStationActivity)
            .inflate(R.layout.item_view_create_station_ctrl_point, ll_ctrl_point_root, false)
        ll_ctrl_point_root.addView(view2)

        val checkBox = view2.findViewById<CheckBox>(R.id.bx_cs_point_name)

        checkBox.isChecked = mObserPoints.any { it.id == point?.id}

        val tv_cs_point_name = view2.findViewById<TextView>(R.id.tv_cs_point_name)
        tv_cs_point_name.text = point?.pointName

        val tv_cs_point_x = view2.findViewById<TextView>(R.id.tv_cs_point_x)
        if (point != null) {
            tv_cs_point_x.text = Helper.formateDecimal(point.pointX).toString()
        }

        val tv_cs_point_y = view2.findViewById<TextView>(R.id.tv_cs_point_y)
        if (point != null) {
            tv_cs_point_y.text = Helper.formateDecimal(point.pointY).toString()
        }

        val tv_cs_point_z = view2.findViewById<TextView>(R.id.tv_cs_point_z)
        if (point != null) {
            tv_cs_point_z.text = Helper.formateDecimal(point.pointZ).toString()
        }

        view2.findViewById<LinearLayout>(R.id.ll_cs_item_root).setOnClickListener {
            checkBox.isChecked = !checkBox.isChecked
            if (checkBox.isChecked) {
                if (point != null) {
                    mObserPoints.add(point)
                }
            } else{
                if (point != null) {
                    mObserPoints.remove(point)
                }
            }

            updateObserverUI()
        }

    }

    //更新观测点UI
    private fun updateObserverUI() {
        ll_obser_point_root.removeAllViews()
        val view_obser_title = LayoutInflater.from(this@CreateStationActivity).inflate(R.layout.item_create_station_observ_title, ll_ctrl_point_root, false)
        ll_obser_point_root.addView(view_obser_title)
        mObserPoints.forEach { point->
            val view_obser_valu = LayoutInflater.from(this@CreateStationActivity).inflate(R.layout.item_create_station_observ_value, ll_ctrl_point_root, false)
            ll_obser_point_root.addView(view_obser_valu)
            val tvname = view_obser_valu.findViewById<TextView>(R.id.tv_cs_observ_pointname)
            val tvhz = view_obser_valu.findViewById<TextView>(R.id.tv_cs_observ_hz)
            val tvda = view_obser_valu.findViewById<TextView>(R.id.tv_cs_observ_da)
            val tvsd = view_obser_valu.findViewById<TextView>(R.id.tv_cs_observ_sd)
            val tvstat = view_obser_valu.findViewById<TextView>(R.id.tv_cs_observ_stat)

            tvname.text = point.pointName

            if (mObservations.any { it.pointId == point.id}) {
                point.pointHz?.let {
                    tvhz.text = Helper.radiansToDMSString(it)
                }

                point.pointV?.let {
                    tvda.text = Helper.radiansToDMSString(it)
                }

                point.pointSD?.let {
                    tvsd.text = Helper.formateDecimal(it).toString()
                }
            }

            tvstat.setOnClickListener {

                AlertDialog.Builder(this@CreateStationActivity)
                    .setTitle("提示")
                    .setMessage("请确定仪器是否已经照准控制点${point.pointName}")
                    .setPositiveButton("确定") { dialog, _ ->

                        if (mRadioSelectIndex == -1) {
                            CentreToast.instance.show("请先选择反射介质", false)
                        } else {
                            startOberserv(point)
                        }
                        dialog.dismiss()
                    }
                    .setNegativeButton("取消") { dialog, _ ->
                        dialog.dismiss()
                    }
                    .show()
            }
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){
            //蓝牙设备
            R.id.tv_ct_goto_bluetooth->{
                val intent = Intent()
                intent.setClass(this@CreateStationActivity, BluetoolsActivity::class.java)
                activityLauncher?.launch(intent)
            }
            //手动输入模式
            R.id.tv_goto_gruest_create_station->{
                val intent = Intent()
                intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                intent.setClass(this@CreateStationActivity, CreateStationGuesterActivity::class.java)
                activityLauncher?.launch(intent)
            }
            //断开连接
            R.id.tv_ct_disconnect_bluetooth->{
                CentreToast.instance.showText("暂未开发")
            }

            R.id.iv_cs_docollected_lightoff->{
                if (!isBluetoothConnected) {
                    CentreToast.instance.show("请先连接仪器", false)
                    return
                }

                geoComHelper.startExecution(listOf(GeoComCommon.EDM_Laserpointer(false)))
            }

            R.id.iv_cs_docollected_lighton->{
                if (!isBluetoothConnected) {
                    CentreToast.instance.show("请先连接仪器", false)
                    return
                }

                geoComHelper.startExecution(listOf(GeoComCommon.EDM_Laserpointer(true)))
            }

            //添加控制点
            R.id.tv_ct_add_basep->{
                val intent = Intent()
                intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                intent.putExtra(CREATE_STATION_BASE_POINT_TPYE, 1)
                intent.setClass(this@CreateStationActivity, CreatePointActivity::class.java)
                activityLauncher?.launch(intent)
            }
            //从库中选择
            R.id.tv_ct_choice_basep->{
                val intent = Intent()
                intent.putExtra(KEY_INTENT_PROJET_ID, projectId)
                intent.putExtra(KEY_INTENT_OBJECT_ID, objectId)
                intent.putExtra(CREATE_STATION_CTRL_POINT_LIST, mCtrlPoints)
                intent.setClass(this@CreateStationActivity, CreateStationForCtrlPActivity::class.java)
                activityLauncher?.launch(intent)
            }
            //批量导入
            R.id.tv_ct_inseert_basep->{
                CentreToast.instance.showText("暂未开发")
            }

            //手动修改
            R.id.tv_ct_update_observ_p->{
                CentreToast.instance.showText("暂未开发")
            }
            //清空观测值
            R.id.tv_ct_clear_observ_p->{
                CentreToast.instance.showText("暂未开发")
            }
            //选择反射介质
            R.id.tv_cs_docollected_mirror->{
                if (!isBluetoothConnected) {
                    CentreToast.instance.show("请先连接仪器", false)
                    return
                }

                RadioDialogHelper.Builder(this)
                    .setTitle("请选择")
                    .setItems(listOf(
                        RadioDialogHelper.RadioBean(0x3001, "徕卡圆棱镜"),
                        RadioDialogHelper.RadioBean(0x3002, "徕卡小棱镜"),
                        RadioDialogHelper.RadioBean(0x3002, "徕卡反射片")))
                    .setSelectedIndex(mRadioSelectIndex)
                    .setOnItemSelectedListener { position, radioBean ->
                        mRadioSelectIndex = position
                        Log.i("CreateStationActivity", "反射介质: ${radioBean.content}, position = $position")
                        val text = "反射介质 ${radioBean.content}"
                        val spannableString = SpannableString(text)
                        spannableString.setSpan(ForegroundColorSpan("#4c4c4c".toColorInt()), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                        spannableString.setSpan(ForegroundColorSpan("#C80505".toColorInt()), 4, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
                        tvSelectedMirror.text = spannableString

                        //根据选择的反射介质，测距模式、

                        if (position == 0) {
                            //徕卡圆棱镜       测距模式：高精度模式     棱镜类型 0
                            geoComHelper.startExecution(listOf(GeoComCommon.BAP_SetPrismType("0"),  GeoComCommon.TMC_SetEdmMode(),
                                GeoComCommon.BAP_GetPrismType, GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetPrismCorr))
                        }

                        if (position == 1) {
                            //徕卡小棱镜       测距模式：标准模式       棱镜类型 1
                            geoComHelper.startExecution(listOf(GeoComCommon.BAP_SetPrismType("1"),  GeoComCommon.TMC_SetEdmMode(),
                                GeoComCommon.BAP_GetPrismType, GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetPrismCorr))
                        }

                        if (position == 2) {
                            //注意：设置模式如果是高精度模式，全站仪会自动把介质置为圆棱镜
                            //徕卡反射片       测距模式：标准模式       棱镜类型 2
                            geoComHelper.startExecution(listOf(GeoComCommon.BAP_SetPrismType("2"), GeoComCommon.TMC_SetEdmMode("1"),
                                GeoComCommon.BAP_GetPrismType, GeoComCommon.TMC_GetEdmMode, GeoComCommon.TMC_GetPrismCorr))
                        }

                    }.build().show()
            }

            //开始计算
            R.id.tv_ct_caculat_st->{


                if (mObservations.isEmpty() || mObservations.size <= 2) {
                    CentreToast.instance.show("观测数据必须大于2个", false)
                    return
                }


                for (i in 0..mObserPoints.size-1){
                    Log.i("CreateStationActivity","${mObserPoints[i].pointName}, " +
                            "x=${mObserPoints[i].pointX}, " +
                            "y=${mObserPoints[i].pointY}, " +
                            "z=${mObserPoints[i].pointZ}," +
                            "hz=${mObservations[i].horizontalAngle}, " +
                            "va=${mObservations[i].verticalAngle}, " +
                            "sd= ${mObservations[i].distance}")
                }



                try {


                    calculationRepository = RearIntersectionAlgorithm.calculateStationPosition(mObserPoints, mObservations)

                    val result = calculationRepository.result
                    val nonCompliantPoints = calculationRepository.nonCompliantPoints
                    val verificationResults = calculationRepository.verificationResults

                    if (result.isConverged && result.isVerificationPassed) {
                        tv_cs_caluation_result.setTextColor(ContextCompat.getColor(this@CreateStationActivity, android.R.color.holo_green_dark))
                        tv_cs_caluation_result.text = "成功"
                        finallCalculationRlt = true
                        Log.i("CreateStationActivity", "后方交会计算成功：测站坐标：(${result.stationX}, ${result.stationY}, ${result.stationZ})")

                        if (result.isThirdOrderStandardMet) {
                            tv_cs_caluation_warn.visibility = View.GONE
                            Log.i("CreateStationActivity","计算结果符合三等平面控制测量标准")
                        } else {
                            tv_cs_caluation_warn.visibility = View.VISIBLE
                            tv_cs_caluation_warn.text = "警告：计算结果不符合三等标准,"
                            Log.i("CreateStationActivity","警告：计算结果不符合三等标准\n不符合标准的控制点：${nonCompliantPoints.joinToString()}")
                            Log.i("CreateStationActivity","不符合标准的控制点：${nonCompliantPoints.joinToString()}")
                        }

                    } else {
                        tv_cs_caluation_result.setTextColor(ContextCompat.getColor(this@CreateStationActivity, android.R.color.holo_red_dark))
                        tv_cs_caluation_result.text = "失败"
                        finallCalculationRlt = false
                        Log.i("CreateStationActivity", "未收敛且所有控制点均未通过验证")
                    }

                    tv_cs_x.text = "北坐标(X)\n${Helper.formateDecimal(result.stationX).toString()}"
                    tv_cs_y.text = "东坐标(Y)\n${Helper.formateDecimal(result.stationY).toString()}"
                    tv_cs_z.text = "高程(Z)\n${Helper.formateDecimal(result.stationZ).toString()}"


                    ll_cs_caluation_root.removeAllViews()

                    verificationResults.forEach { verification->

                        val title = "控制点[${verification.pointName}]验证汇总:\n"
                        val vcheck = "    垂直角残差: ${Helper.degrees(verification.zenithAngleDifference)}" +
                                "（阈值: ${RearIntersectionAlgorithm.DEFAULT_ZENITH_ANGLE_THRESHOLD_SECONDS}秒）→ " +
                                "${if (verification.isZenithAnglePassed) "通过" else "失败"}\n"
                        val hcheck = "    水平距残差: ${String.format("%.6f", verification.distanceDifference)} m" +
                                "（阈值: ${RearIntersectionAlgorithm.DEFAULT_POSITION_THRESHOLD} m）→ " +
                                "${if (verification.isDistancePassed) "通过" else "失败"}\n"
                        val hzcheck = "    水平角残差: ${Helper.degrees(verification.angleDifference)}" +
                                "（阈值: ${RearIntersectionAlgorithm.DEFAULT_ANGLE_THRESHOLD_SECONDS}秒）→ " +
                                "${if (verification.isAnglePassed) "通过" else "失败"}\n"
                        val checkrlt = "    整体验证结果: ${if (verification.isAnglePassed && 
                            verification.isDistancePassed && verification.isZenithAnglePassed) "通过" else "失败"}\n"

                        val rlt = title + vcheck + hcheck + hzcheck + checkrlt

                        val rltText = TextView(this@CreateStationActivity)
                        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                        layoutParams.gravity = Gravity.CENTER_VERTICAL
                        rltText.layoutParams = layoutParams
                        rltText.setTextColor(ContextCompat.getColor(this@CreateStationActivity, R.color.common_text_colr))
                        rltText.text = rlt
                        ll_cs_caluation_root.addView(rltText)
                    }


                } catch (e:Exception) {
                    Log.i("CreateStationActivity", "后方交会计算异常：${e.message}")
                }




            }
            //保存计算值
            R.id.tv_ct_save_caculat->{
                if (TextUtils.isEmpty(edit_cd_name.text)) {
                    CentreToast.instance.show("测站名称不可为空", false)
                    return
                }

                if (TextUtils.isEmpty(edit_cs_eqhight.text)) {
                    CentreToast.instance.show("仪器高度不可为空", false)
                    return
                }


                lifecycleScope.launch {
                    val x = calculationRepository.result.stationX
                    val y = calculationRepository.result.stationY
                    val z = calculationRepository.result.stationZ
                    val station = MonitoringStation(monitoringObjectId= objectId, stationName = edit_cd_name.text.toString(),
                        stationCode= UUID.randomUUID().toString(), stationX = x, stationY = y, stationZ = z,
                        stationHeight= edit_cs_eqhight.text.toString().toDouble(), stationDescription="", isReferenceStation= false,
                        createTime = Helper.formatTimestamp(System.currentTimeMillis()), updateTime ="")
                    val result = database.saveCalculationResult(station, calculationRepository)

                    withContext(Dispatchers.Main){
                        if (result) {
                            CentreToast.instance.show("保存成功", true)
                            finish()
                        } else {
                            CentreToast.instance.show("保存失败", true)
                        }
                    }
                }
            }
        }
    }

    // 初始化回调函数
    private fun initGeoComCallback() {
        if (geoComCallback == null) {
            geoComCallback = { results, params ->
                results.forEach { result ->
                    Log.i("CreateStationActivity", "name = ${result.name}, command=${result.command}, result=${result.result}")
                    when (result.name) {

                        GeoComCommon.TMC_DoMeasure.name ->{
                            val list = Helper.parseJson(result.result)
                            var rc = list[0]

                            if (rc != "0") {
                                safeResumeWithFailure("执行距离测量模式失败")
                            }
                        }

                        GeoComCommon.TMC_GetFace.name->{
                            val list = Helper.parseJson(result.result)
                            if (list[1] == "0") {
                                Log.i("DoCollectedActivity", "当前是盘左")
                                geoComHelper.startExecution(listOf(GeoComCommon.BAP_SearchTarget))
                            } else {
                                Log.i("DoCollectedActivity", "当前是盘右")
                                geoComHelper.startExecution(listOf(GeoComCommon.AUT_ChangeFace))
                            }
                        }

                        GeoComCommon.AUT_ChangeFace.name->{
                            if (result.result != "-1" ) {
                                val list = Helper.parseJson(result.result)
                                if (list[0] == "0") {
                                    geoComHelper.startExecution(listOf(GeoComCommon.TMC_GetFace))
                                }
                            }
                        }

                        GeoComCommon.BAP_SearchTarget.name -> {
                            if (result.result == "-1") {
                                safeResumeWithFailure("未找到目标")
                            } else {
                                geoComHelper.startExecution(listOf(GeoComCommon.TMC_DoMeasure("1"),GeoComCommon.TMC_GetSimpleMea))
                            }
                        }

                        GeoComCommon.TMC_GetSimpleMea.name->{
                            val list = Helper.parseJson(result.result)
                            if (list.size > 1) {

                                val strHz = Helper.radiansToDMSString(list[1].toDouble())
                                val strV = Helper.radiansToDMSString(list[2].toDouble())
                                val strDist = Helper.formateDecimal(list[3].toDouble(), "#.####")
                                Log.i("CreateStationActivity", "获取当前测点 水平角度:$strHz, 垂直角：$strV, 斜距：$strDist")

                                //查询当前测点下是否有观测数据，有则更新，没有则创建
                                val tempMap = HashMap<String, Any>()
                                tempMap[CREATE_STATION_HZ] = list[1].toDouble()
                                tempMap[CREATE_STATION_VA] = list[2].toDouble()
                                tempMap[CREATE_STATION_SD] = list[3].toDouble()
                                safeResumeWithSuccess(tempMap)
                            }else {
                                safeResumeWithFailure("测量结果失败")
                            }
                        }

                        GeoComCommon.TMC_GetPrismCorr.name ->{
                            val list = Helper.parseJson(result.result)
                            var prismCorr = list[1]
                            if (!TextUtils.isEmpty(prismCorr)) {

                                prismCorr =  Helper.formateDecimal(prismCorr.toDouble()*100, "##.#").toString()
                            }
                            Log.i("CreateStationActivity", "棱镜常数是：$prismCorr")
                            tv_cs_mirror_c.text = prismCorr
                        }

                        GeoComCommon.CSV_GetInstrumentName.name->{
                            val list = Helper.parseJson(result.result)
                            if (!TextUtils.isEmpty(list[1])){
                                monitorStauts.equmentName = list[1]
                                viewModel.updateState(monitorStauts)
                            }
                        }

                        GeoComCommon.TMC_GetInclineSwitch.name->{
                            if (CustomApplication.isAppInForeground) {
                                val list = Helper.parseJson(result.result)
                                if ("1" != list[1]){
                                    monitorStauts.getInclineSwitch = false
                                } else {
                                    monitorStauts.getInclineSwitch = true
                                }
                                viewModel.updateState(monitorStauts)
                            }
                        }

                        GeoComCommon.TMC_GetAngSwitch.name->{
                            val list = Helper.parseJson(result.result)
                            val inClineCorr     = list[1]   //倾斜校正状态
                            val standAxisCorr   = list[2]   //竖轴校正状态
                            val collimationCorr = list[3]   //视准轴校正状态
                            val tiltaxisCorr    = list[4]   //横轴校正状态

                            if ("1" != inClineCorr){
                                monitorStauts.inClineCorr = false
                            } else {
                                monitorStauts.inClineCorr = true
                            }
                            if ("1" != standAxisCorr){
                                monitorStauts.standAxisCorr = false
                            } else {
                                monitorStauts.standAxisCorr = true
                            }

                            if ("1" != collimationCorr){
                                monitorStauts.collimationCorr = false
                            } else {
                                monitorStauts.collimationCorr = true
                            }
                            if ("1" != tiltaxisCorr){
                                monitorStauts.tiltaxisCorr = false
                            } else {
                                monitorStauts.tiltaxisCorr = true
                            }

                            viewModel.updateState(monitorStauts)
                        }

                        GeoComCommon.BAP_GetPrismType.name->{
                            val list = Helper.parseJson(result.result)
                            val mirrorType = list[1]
                            Log.i("CreateStationActivity", "棱镜类型是：$mirrorType")
                            var strType = ""
                            when(mirrorType) {
                                "0" -> strType = "圆棱镜"
                                "1" -> strType = "迷你棱镜"
                                "2" -> strType = "反射片"
                            }

                            viewModel.updateMirrorType(strType)
                        }

                        GeoComCommon.TMC_GetEdmMode.name ->{
                            val list = Helper.parseJson(result.result)
                            prismType = list[1]
                            Log.i("CreateStationActivity", "测量模式是：$prismType")
                            var strType = ""
                            when(prismType) {
                                "0" -> strType = "标准"
                                "1" -> strType = "快速"
                                "2" -> strType = "高精"
                                "3" -> strType = "跟踪"
                            }
                            viewModel.updateMeasureModle(strType)
                        }

                        GeoComCommon.TMC_GetAngle1.name->{
                            if (result.result == "-1") {
                                monitorStauts.mIncline = false
                            } else {
                                val list = Helper.parseJson(result.result)
                                val crossIncline = list[5]      //双精度横向倾角（单位：弧度）
                                val lengthIncline = list[6]     //双精度横向倾角（单位：弧度）
                                val strT = Helper.radiansToDMSString(crossIncline.toDouble())
                                val strL = Helper.radiansToDMSString(lengthIncline.toDouble())

                                val secT = Helper.radiansToSecond(crossIncline.toDouble()).absoluteValue
                                val secL = Helper.radiansToSecond(lengthIncline.toDouble()).absoluteValue

                                if (secT < 180 && secL < 180) {
                                    val msg = "L:$strL ,  T:$strT"
                                    Log.i("CreateStationActivity", msg)
                                    monitorStauts.mIncline = true
                                } else {
                                    monitorStauts.mIncline = false
                                }
                            }
                            viewModel.updateState(monitorStauts)
                        }
                    }
                }
            }
        }
    }
    //初始化任务队列监听
    private fun initTaskQueueListener(){
        bluetoothQueue.setListener(object : BluetoothTaskListener<String> {

            override fun onTaskStarted(taskId: String) {
                // 任务开始：更新UI（如显示"正在执行任务XXX"）
                loadingDialog?.show()
                Log.d("CreateStationActivity", "任务 $taskId 开始执行")
            }

            override fun onTaskFailed(taskId: String, reason: String) {
                Log.e("CreateStationActivity", "任务 $taskId 执行失败：$reason")
                CentreToast.instance.showText("任务 $taskId 执行失败：$reason")
            }

            override fun onTaskSuccess(taskId: String, params:Map<String, Any>) {
                // 任务成功：更新UI（如显示"任务XXX成功"
                val hz = params.get(CREATE_STATION_HZ) as Double
                val va = params.get(CREATE_STATION_VA) as Double
                val sd = params.get(CREATE_STATION_SD) as Double
                Log.e("CreateStationActivity", "$taskId 任务成功：hz=$hz, va =$va, sd=$sd")



                if (mObservations.any{it.id == taskId.toInt()}) {
                    val observ = mObservations.find { it.id ==  taskId.toInt()}
                    observ?.horizontalAngle = hz
                    observ?.verticalAngle = va
                    observ?.distance=sd
                } else {
                    val observ = MonitoringObservation(pointId = taskId.toInt(), horizontalAngle = hz, verticalAngle = va, distance=sd,
                        temperature = 30.0, pressure = 0.0, humidity = 10.0, correctedX= 0.0,
                        correctedY = 0.0, correctedZ = 0.0, dx = 0.0, dy = 0.0, dz = 0.0, totalDisplacement = 0.0 )
                    mObservations.add(observ)
                }

                mObserPoints.forEach {
                    if (it.id == taskId.toInt()) {
                        it.pointHz = hz
                        it.pointV = va
                        it.pointSD = sd
                        it.mirrorHeight = 0.0
                    }
                }
                updateObserverUI()
            }

            override fun onQueueCompleted() {
                // 所有任务完成：更新UI（如显示"全部任务执行完成"）
                Log.d("CreateStationActivity", "队列中所有任务执行完成")
                loadingDialog?.dismiss()
            }

            override fun onQueueAborted(lastFailedTaskId: String, reason: String) {
                // 队列终止：更新UI（如显示"任务XXX失败，队列终止"）
                Log.e("CreateStationActivity", "队列终止，最后失败的任务：$lastFailedTaskId，原因：$reason")
                loadingDialog?.dismiss()
            }
        })
    }

    //开始观测
    private fun startOberserv(point:MonitoringPoint){
        val taskid = point.id.toString()
        bluetoothQueue.addBluetoothTask(taskid, createBluetoothTask())
    }

    private fun createBluetoothTask():BluetoothTask{
        return suspend {
            suspendCancellableCoroutine { continuation ->
                // 重置状态
                isResumed.set(false)
                currentContinuation = continuation

                try {

                    // 启动初始任务
                    geoComHelper.startExecution(listOf(GeoComCommon.TMC_GetFace))

                    // 处理协程取消
                    continuation.invokeOnCancellation {
                        if (isResumed.compareAndSet(false, true)) {
                            currentContinuation = null
                        }
                    }
                } catch (e: Exception) {
                    safeResumeWithFailure("未知错误: ${e.message}")
                }
            }
        }
    }

    // 安全恢复协程并返回成功结果
    private fun safeResumeWithSuccess(params:Map<String, Any>) {
        if (isResumed.compareAndSet(false, true)) {
            currentContinuation?.resume(BluetoothTaskResult.Success(params)) {
                currentContinuation = null
            }
        }
    }

    // 安全恢复协程并返回失败结果
    private fun safeResumeWithFailure(reason: String) {
        if (isResumed.compareAndSet(false, true)) {
            currentContinuation?.resume(BluetoothTaskResult.Failure(reason)) {
                currentContinuation = null
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        geoComHelper.removeResultCallback(geoComCallback!!)
    }

    override fun getLayoutId(): Int {

        return R.layout.activity_create_monitoring_station
    }
}